package com.csc.yunting.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.atguigu.srb.base.exception.SrbException;
import com.atguigu.srb.base.result.ResponseEnum;
import com.csc.yunting.oss.config.OssProperties;
import com.csc.yunting.oss.service.OssService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file, String module) {
        //获取上传的文件名
        String fileName= file.getOriginalFilename();
        //1、上传的文件 在oss桶内保存的路径和文件名称
        String objectName = module+new DateTime().toString("/yyyy/MM/dd/")
                + System.currentTimeMillis()+"_"+
                UUID.randomUUID().toString().substring(0,6)
                +fileName.substring(fileName.lastIndexOf("."));//截取文件扩展名
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.ACCESS_KEY_ID, OssProperties.ACCESS_KEY_SECRET);
        try {
            //获取上传文件的 输入流
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssProperties.BUCKET_NAME,
                    objectName, inputStream);
            ossClient.putObject(putObjectRequest);

            String imgPath = "https://"+OssProperties.BUCKET_NAME+
                    ".oss-cn-beijing.aliyuncs.com/"+objectName;
            System.out.println(imgPath);
            return imgPath;
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
            throw new SrbException(ResponseEnum.UPLOAD_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void deleteFile(String path) {
        //1、要删除的文件在桶内的路径+文件名
        String objectName = path.substring(("https://"+
                OssProperties.BUCKET_NAME+".oss-cn-beijing.aliyuncs.com/").length());
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.ACCESS_KEY_ID, OssProperties.ACCESS_KEY_SECRET);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
            throw new SrbException(ResponseEnum.DELETE_FILE_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
